import React, { useState, useEffect, useRef } from 'react';
import "./App.css"
import axios from 'axios';

interface Message {
  from: string;
  content: string;
  timestamp: string;
  isSelf?: boolean;
}

interface User {
  _id: string;
  username: string;
  email: string;
}

const Yao: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [message, setMessage] = useState('');
  const [users, setUsers] = useState<User[]>([]);
  const [messages, setMessages] = useState<Message[]>([]);
  const [onlineUsers, setOnlineUsers] = useState<string[]>([]);
  const [ws, setWs] = useState<WebSocket | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [target, setTarget] = useState<string | null>(null);
  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };
  const getUsers = async () => {
    axios.get('http://127.0.0.1:3000/zt/user').then(res => {
      setUsers(res.data.data)
    })
  };
  const handleLogin = async () => {
    const userData = localStorage.getItem('user');
    if (!userData) {
      alert('请先登录');
      return;
    }
    const user1 = JSON.parse(userData)?.[0];
    if (!user1) {
      alert('用户数据无效');
      return;
    }
    if (!user1) {
      alert('请先登录');
      return;
    } else {
      setUser({
        _id: user1._id,
        username: user1.username,
        email: user1.email
      });
    }

    try {
      const userData = user1;
      setUser(userData);

      // 建立WebSocket连接（携带用户ID参数）
      const websocket = new WebSocket(`ws://localhost:3001?userId=${userData._id}`);

      // WebSocket连接成功回调
      websocket.onopen = () => {
        console.log('WebSocket连接已建立');
        setWs(websocket);
      };

      // 实时消息处理
      websocket.onmessage = (e) => {
        const data = JSON.parse(e.data);
        switch (data.type) {
          // 更新在线用户列表
          case 'online-users':
            setOnlineUsers(data.users);
            break;

          // 处理普通消息
          case 'message':
            setMessages(prev => {
              // 防止重复消息
              const exists = prev.some(msg => 
                msg.timestamp === data.timestamp &&
                msg.from === data.from
              );
              return exists ? prev : [...prev, {
                ...data,
                isSelf: data.from === userData._id,
                timestamp: data.timestamp || new Date().toISOString()
              }];
            });
            break;

          // 处理@提及通知
          case 'mention':
            if (data.to === userData._id) {
              // 浏览器通知处理逻辑
              if (Notification.permission === 'granted') {
                new Notification(`有人提到了你`, { body: `${data.content}` });
              } else {
                alert(`你被提及：${data.content}`);
              }
            }
            break;
        }
      };

      // 连接关闭处理
      websocket.onclose = function (event) {
        console.log('WebSocket连接关闭', 'Code:', event.code, 'Reason:', event.reason);
      };

    } catch (error) {
      alert(message);
    }
  };
  useEffect(scrollToBottom, [messages]);

  // 消息存储初始化：从本地存储加载历史消息
  useEffect(() => {
    getUsers()
    if (user) {
      const savedMessages = localStorage.getItem(`chatMessages_${user._id}`);
      if (savedMessages) {
        try {
          const parsedMessages = JSON.parse(savedMessages);
          setMessages(parsedMessages);
        } catch (error) {
          console.error("Failed to parse saved messages:", error);
        }
      }
    }
  }, [user]);

  // 保存消息到本地存储
  useEffect(() => {
    if (user) {
      localStorage.setItem(`chatMessages_${user._id}`, JSON.stringify(messages));
    }
  }, [messages, user]);

  // 跨标签页同步
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (user && e.key === `chatMessages_${user._id}` && e.newValue) {
        try {
          const newMessages = JSON.parse(e.newValue);
          setMessages(newMessages);
        } catch (error) {
          console.error("Failed to parse synced messages:", error);
        }
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [user]);

  // 浏览器通知权限请求
  useEffect(() => {
    if (user && Notification.permission !== 'denied') {
      Notification.requestPermission();
    }
  }, [user]);

  // 用户登录处理
 

  // 消息发送逻辑（含@提及处理）
  const sendMessage = () => {
    if (!message.trim()) return;

    // 使用正则表达式匹配@提及的用户名
    const mentionRegex = /@(\w+)(?=\s|$)/g;
    const mentionedUsers = new Set<string>();
    let match;
    while ((match = mentionRegex.exec(message)) !== null) {
      mentionedUsers.add(match[1]);
    }

    // 发送普通消息
    if (ws && target && message) {
      const timestamp = new Date().toISOString();
      ws.send(JSON.stringify({
        type: 'message',
        to: target,
        content: message,
        timestamp
      }));

      // 发送@提及通知给每个被提到的用户
      Array.from(mentionedUsers).forEach(mentionedId => {
        ws.send(JSON.stringify({
          type: 'mention',
          to: mentionedId,
          from: user!._id,
          content: `在消息中提到了你：${message}`,
          timestamp
        }));
      });

      // 更新本地消息状态
      setMessages(prev => [...prev, {
        from: user!._id,
        content: message,
        timestamp,
        isSelf: true
      }]);
      setMessage('');
    }
  };

  // 界面渲染部分保持不变
  return (
    <div className="wechat-container">
      {!user ? (
        <div className="login-screen">
          <div className="wechat-logo">
            <div className="logo-circle green"></div>
            <div className="logo-circle white"></div>
          </div>
          <button onClick={handleLogin} className="wechat-login-btn">
            点击进入
          </button>
        </div>
      ) : (
        <div className="wechat-main">
          <div className="sidebar">
            <div className="user-header">
              <div className="user-avatar">{user.username[0]}</div>
              <h3>{user.username}</h3>

            </div>
            <div className="online-list">
              <h4>在线用户 ({onlineUsers.length})</h4>
              <ul>
                {onlineUsers.map(id => (
                  <li
                    key={id}
                    className={id == target ? 'current-user' : ''}
                    onClick={() => {
                      setTarget(id)
                    }}
                  >
                    <span className="online-dot"></span>
                    {id === user._id ? '我' : id}
                  </li>
                ))}
                <h4>离线用户 ({users.length-onlineUsers.length})</h4>
                {users.map(item => (
                  onlineUsers.includes(item._id)? null : (
                  <li
                    key={item._id}
                    className={item._id == target? 'current-user' : ''}
                    onClick={() => {
                      setTarget(item._id)
                    }}
                  >
                    <span className="online-dott"></span>
                     {item.username}
                  </li>
                  )
                ))}
                
              </ul>
            </div>
          </div>

          <div className="chat-area">
            <div className="message-list">
              {messages.map((msg, i) => (
                msg.from === target || msg.from === user._id ? 
                <div
                  key={i}
                  className={`message-bubble ${msg.isSelf ? 'self' : 'other'}`}
                  onClick={() => {
                    console.log(msg);
                    
                  }}
                >
                  {!msg.isSelf && <div className="user-avatar-small">{msg.from[0]}</div>}
                  <div className="bubble-content">
                    <div className="message-text">{msg.content}</div>
                    <div className="message-time">
                      {new Date(msg.timestamp).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </div>
                </div>: null
              ))}
              <div ref={messagesEndRef} />
            </div>

            <div className="input-box">
              <input
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={e => e.key === 'Enter' && sendMessage()}
                placeholder="输入消息..."
              />
              <button onClick={sendMessage} className="send-btn">
                <span className="icon-send">➤</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Yao;